package com.ruoyi.business.controller;

import com.ruoyi.business.service.ISysFileInfoService;
import com.ruoyi.business.vo.SysFileInfoVo;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.business.vo.TVideosVo;
import com.ruoyi.business.service.ITVideosService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;

/**
 * 视频Controller
 *
 * @author user
 * @date 2023-05-06
 */
@Api(tags = "视频Controller")
@RestController
@RequestMapping("/business/videos")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class TVideosController extends BaseController {

    private final ITVideosService tVideosService;
    private final ISysFileInfoService sysFileInfoService;

    @ApiOperation("查询视频列表")
    @PreAuthorize("@ss.hasPermi('business:videos:list')")
    @GetMapping("/list")
    public TableDataInfo<TVideosVo> list(TVideosVo entity) {
        return tVideosService.queryList(entity);
    }

    @ApiOperation("查询视频所有列表")
    @GetMapping("/listAll")
    public AjaxResult listAll(TVideosVo entity) {
        return AjaxResult.success("查询成功", tVideosService.queryAll(entity));
    }

    @ApiOperation("导出视频列表")
    @PreAuthorize("@ss.hasPermi('business:videos:export')")
    @Log(title = "视频", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TVideosVo entity) {
        List<TVideosVo> list = tVideosService.queryAll(entity);
        ExcelUtil<TVideosVo> util = new ExcelUtil<>(TVideosVo.class);
        util.exportExcel(response, list, "视频数据");
    }

    @ApiOperation("获取视频详细信息")
    @PreAuthorize("@ss.hasPermi('business:videos:query')")
    @GetMapping(value = "/getInfo/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        TVideosVo tVideosVo = tVideosService.queryById(id);
        Integer fileId = Integer.parseInt(tVideosVo.getFileId().toString());
        //根据fileId查询文件
        SysFileInfoVo byFileId = sysFileInfoService.getByFileId(fileId);
        tVideosVo.setSysFileInfo(byFileId);
        return AjaxResult.success("查询成功", tVideosVo);
    }

    @ApiOperation("新增视频")
    @PreAuthorize("@ss.hasPermi('business:videos:add')")
    @Log(title = "视频", businessType = BusinessType.INSERT)
    @PostMapping("add")
    public AjaxResult add(@RequestBody TVideosVo entity) {
        return toAjax(tVideosService.save(entity));
    }

    @ApiOperation("修改视频")
    @PreAuthorize("@ss.hasPermi('business:videos:edit')")
    @Log(title = "视频", businessType = BusinessType.UPDATE)
    @PostMapping("edit")
    public AjaxResult edit(@RequestBody TVideosVo entity) {
        return toAjax(tVideosService.updateById(entity));
    }

    @ApiOperation("删除视频")
    @PreAuthorize("@ss.hasPermi('business:videos:remove')")
    @Log(title = "视频", businessType = BusinessType.DELETE)
    @GetMapping("/remove/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tVideosService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }

    /**
     * 根据文件id返回文件流
     */
    @GetMapping("/getBlobByFileId/{ids}")
    public void getBlobByFileId(@PathVariable Long[] ids, HttpServletResponse response) {
        long id = ids[0];
        SysFileInfoVo info = sysFileInfoService.getByFileId(Integer.parseInt(String.valueOf(id)));
        String filePath = info.getFilePath().replace("profile", "");
        String fileType = filePath.substring(filePath.lastIndexOf("."));
        String path;
        if (fileType.equals(".xls") || fileType.equals(".xlsx") || fileType.equals(".doc")
                || fileType.equals(".docx") || fileType.equals(".ppt") || fileType.equals(".pptx")) {
            path = System.getProperty("user.dir") + "/uploadPath/" + filePath.substring(0, filePath.lastIndexOf(".")) + ".pdf";
            response.setContentType("application/pdf");
        } else if (fileType.equals(".jpg") || fileType.equals(".jpeg") || fileType.equals(".gif") || fileType.equals(".png")) {
            path = System.getProperty("user.dir") + "/uploadPath/" + filePath;
            response.setContentType("image/jpeg,image/jpg,image/png,image/gif");
        } else {
            path = System.getProperty("user.dir") + "/uploadPath/" + filePath;
            response.setContentType("application/zip");
        }
        File file = new File(path);
        try {
            response.setCharacterEncoding("UTF-8");
            InputStream stream = new FileInputStream(file);
            ServletOutputStream out = response.getOutputStream();
            byte buff[] = new byte[1024];
            int length = 0;
            while ((length = stream.read(buff)) > 0) {
                out.write(buff, 0, length);
            }
            stream.close();
            out.close();
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
